const db = require('../db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

class User {
  static async create(user) {
    const { username, password, phone } = user;
    // 密码加密
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    
    const sql = 'INSERT INTO users (username, password, phone) VALUES (?, ?, ?)';
    const [result] = await db.query(sql, [username, hashedPassword, phone]);
    return result;
  }

  static async findByUsername(username) {
    const sql = 'SELECT * FROM users WHERE username = ?';
    const [rows] = await db.query(sql, [username]);
    return rows[0];
  }

  static async findByPhone(phone) {
    const sql = 'SELECT * FROM users WHERE phone = ?';
    const [rows] = await db.query(sql, [phone]);
    return rows[0];
  }

  static async findById(id) {
    const sql = 'SELECT * FROM users WHERE id = ?';
    const [rows] = await db.query(sql, [id]);
    return rows[0];
  }

  static async verifyPassword(password, hashedPassword) {
    return await bcrypt.compare(password, hashedPassword);
  }

  // 验证token
  static async verifyToken(token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      const user = await this.findById(decoded.id);
      if (!user) {
        return null;
      }
      // 返回用户信息（不包含密码）
      const { password, ...userInfo } = user;
      return userInfo;
    } catch (error) {
      return null;
    }
  }
}

module.exports = User; 